<?php defined('SYSPATH') or die('No direct script access.');

class Form2
{
  public static function select($name, array $options = NULL, $selected = NULL, array $attributes = NULL)
  {
    // Set the input name
    $attributes['name'] = $name;

    if (is_array($selected))
    {
      // This is a multi-select, god save us!
      $attributes['multiple'] = 'multiple';
    }

    if ( ! is_array($selected))
    {
      if ($selected === NULL)
      {
        // Use an empty array
        $selected = array();
      }
      else
      {
        // Convert the selected options to an array
        $selected = array( (string) $selected);
      }
    }

    if (empty($options))
    {
      // There are no options
      $options = '';
    }
    else
    {
      foreach ($options as $value => $data)
      {
        // Force value to be string
        $value = (string) $value;

        // Create a new attribute set for this option
        $option = array('value' => $value);

        if (in_array($value, $selected))
        {
          // This option is selected
          $option['selected'] = 'selected';
        }
        
        $option = array_merge($option,Arr::get($data,'attributes'));
        $name = Arr::get($data,'text');

        // Change the option to the HTML string
        $options[$value] = '<option'.HTML::attributes($option).'>'.HTML::chars($name, FALSE).'</option>';
      }

      // Compile the options into a single string
      $options = "\n".implode("\n", $options)."\n";
    }

    return '<select'.HTML::attributes($attributes).'>'.$options.'</select>';
  }
}
